package es.ibm.santillana.mdm.entryPreview.catalog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.ccd.common.context.AustinContext;
import com.ibm.ccd.common.context.interfaces.ISessionContext;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.OrderedJSONObject;
import com.ibm.pim.attribute.AttributeInstance;
import com.ibm.pim.catalog.Catalog;
import com.ibm.pim.catalog.CatalogManager;
import com.ibm.pim.catalog.item.Item;
import com.ibm.pim.collaboration.CollaborationAreaManager;
import com.ibm.pim.common.ExtendedValidationErrors;
import com.ibm.pim.common.ValidationError;
import com.ibm.pim.common.exceptions.PIMSearchException;
import com.ibm.pim.context.Context;
import com.ibm.pim.context.PIMContextFactory;
import com.ibm.pim.hierarchy.Hierarchy;
import com.ibm.pim.hierarchy.HierarchyManager;
import com.ibm.pim.hierarchy.category.Category;
import com.ibm.pim.lookuptable.LookupTable;
import com.ibm.pim.lookuptable.LookupTableEntry;
import com.ibm.pim.lookuptable.LookupTableManager;
import com.ibm.pim.search.SearchQuery;
import com.ibm.pim.search.SearchResultSet;
import com.ibm.pim.spec.SecondarySpec;
import com.ibm.pim.web.framework.dispatcher.AsyncEnabled;
import com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled;

import es.ibm.santillana.mdm.common.util.ConstSantillana;
import es.ibm.santillana.mdm.common.util.ItemUtils;


public class AsociarArticulo implements AsyncEnabled,RequestResponseEnabled{
	
	//searchqueries catalogos auxiliares
	private static final String QUERY_COMBO_PLAN_EDITORIAL = "select item from catalog('Planes_Editoriales')";
	private static final String QUERY_COMBO_SELLO = "select item from catalog('Sellos')";
	private static final String QUERY_COMBO_ASIGNATURA = "select item from catalog('Asignaturas') where item.category.pk = '";
	private static final String QUERY_COMBO_CURSO = "select item from catalog('Cursos') where item.category.pk = '";
	private static final String CCOMILLA = "'";
	
	//private static String sSpecName = "Especificos - CO-Distribuidora Editora Richmond - Material Marketing";
	private static String sSpecName = "Generales";
	HttpServletRequest request;
	HttpServletResponse response;
	
	Context ctxPIM;
	CatalogManager ctgMan;
	Catalog catalogoMaestro;
	HierarchyManager hyMng;
	CollaborationAreaManager caMng;
	
	//send an json array
	String responseContent ="";

	/* (sin Javadoc) 
	 * @see com.ibm.pim.web.framework.dispatcher.AsyncEnabled#getContentType()
	 */
	public String getContentType() {
		
		return JSON;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.AsyncEnabled#getResponseContent()
	 */
	public String getResponseContent() {
		
		return responseContent;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled#setRequest(javax.servlet.http.HttpServletRequest)
	 */
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled#setResponse(javax.servlet.http.HttpServletResponse)
	 */
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	/**
	 * FlowConfig Method.
	 */
	public void inicializaPacks(){
		ctxPIM = PIMContextFactory.getCurrentContext();
		ctgMan = ctxPIM.getCatalogManager();
		
	}
	

	/**
	 * FlowConfig Method.
	 * @throws IOException 
	 * @throws PIMSearchException 
	 */
	public void obtenerFormulario() throws IOException, PIMSearchException{
		System.out.println("Obtener datos");
		
		AustinContext actx = (AustinContext)request.getSession().getAttribute("ctx");
		AustinContext.setCurrentContext(actx);
		
		String pkArticulo = request.getParameter("pkArticulo");
		String pkSociedad = request.getParameter("pkSociedad");
		String sbWf = request.getParameter("sbWf");
		String sCtgName = request.getParameter("sCtgName");
		System.out.println("Request URI: "+ request.getRequestURI());
		System.out.println("Remote Addr: "+ request.getRemoteAddr());
		System.out.println("PK=" + pkArticulo);
		
		JSONArray aListPack = obtenerDatosFormulario(pkArticulo, pkSociedad, sbWf, sCtgName);
		
		responseContent = aListPack.serialize(true);		
	}
	
	public void obtenerDatosBusqueda() throws PIMSearchException, IOException{
		AustinContext actx = (AustinContext)request.getSession().getAttribute("ctx");
		AustinContext.setCurrentContext(actx);
		
		String pkSociedad = request.getParameter("pkSociedad");
		String sCtgName = request.getParameter("sCtgName");
		String sClave = request.getParameter("sClave");
		String sTitulo = request.getParameter("sTitulo");
		String sPlan = request.getParameter("sPlan");
		String sAsignatura = request.getParameter("sAsignatura");
		String sIsbn = request.getParameter("sIsbn");
		String sSello = request.getParameter("sSello");
		String sCurso = request.getParameter("sCurso");
		if(ctxPIM == null){
			ctxPIM = PIMContextFactory.getCurrentContext();
		}
		hyMng = ctxPIM.getHierarchyManager();
		Hierarchy hySociedadesTipo = hyMng.getHierarchy(ConstSantillana.JERARQUIA_PAISES);
	
		Category catSociedad = hySociedadesTipo.getCategoryByPrimaryKey(pkSociedad);

			
		Collection<SecondarySpec> listaSpecsSoci = catSociedad.getItemSecondarySpecs();
		Iterator <SecondarySpec> itSpecsSoci = listaSpecsSoci.iterator();
		String sSpecSociedad = null;
		String sSpecSearch = null;
		while (itSpecsSoci.hasNext()) {
			SecondarySpec secSpec = itSpecsSoci.next();
			String name = secSpec.getName();
			if (!name.contains("SEARCH")) {
				sSpecSociedad = name;
			}
			else {
				sSpecSearch = name;
			}
		}
		
		
		System.out.println("sSpecSociedad " + sSpecSociedad);
		System.out.println("sSpecSearch " + sSpecSearch);
		
		System.out.println("sPlan: " + sPlan);
		System.out.println("sAsignatura: " + sAsignatura);
		System.out.println("sIsbn: " + sIsbn);
		System.out.println("sSello: " + sSello);
		System.out.println("sCurso: " + sCurso);
		
		
		
		
		
		//query para obtener los posibles elementos del pack
		String sSelect = "select item from catalog('Articulos') where item.category.pk = '"+pkSociedad+CCOMILLA;
		if(sClave.length()>0){
			sSelect = sSelect + " and item['"+ConstSantillana.MAESTRO_ARTICULOS_SPEC + "/Clave'] = "+Integer.parseInt(sClave.trim());
		}
		
		if(sTitulo.length()>0){
			sSelect = sSelect + " and item['"+ConstSantillana.TITULO_CORTO + "'] like '%"+sTitulo.trim()+"%'";
		}
		if(sPlan.length()>0 && !sPlan.equals("NULL")){
			sSelect = sSelect + " and item['"+sSpecSociedad + "/Plan_Editorial'].pk = '"+sPlan.trim()+CCOMILLA;
		}
		if(sAsignatura.length()>0 && !sAsignatura.equals("NULL")){
			sSelect = sSelect + " and item['"+ sSpecSearch + "/Asignatura'].pk = '"+sAsignatura.trim()+CCOMILLA;
		}
		if(sIsbn.length()>0){
			sSelect = sSelect + " and item['"+ConstSantillana.ISBN+"'] like '%"+sIsbn.trim()+"%'";
		}
		if(sSello.length()>0 && !sSello.equals("NULL")){
			sSelect = sSelect + " and item['"+ConstSantillana.SELLO_ID + "'].pk = '"+sSello.trim()+CCOMILLA;
		}
		if(sCurso.length()>0 && !sCurso.equals("NULL")){
			sSelect = sSelect + " and item['"+sSpecSearch + "/Nivel_Escolar/Curso'].pk = '"+sCurso.trim()+CCOMILLA;
		}
		
		System.out.println("Query maravillosa : "+sSelect);
		SearchQuery sqItems = ctxPIM.createSearchQuery(sSelect);
		SearchResultSet rsItems = sqItems.execute();
		ArrayList<Item> aItems = new ArrayList<Item>();
		while (rsItems.next()) {
			aItems.add(rsItems.getItem(1));
			
		}
			
		
		JSONArray aResultado = obtenerInfoArticulos(aItems, catSociedad);
		
		responseContent = aResultado.serialize(true);		
		
	}
	
	
	
	public void agregarReferencia() throws Exception{
		AustinContext actx = (AustinContext)request.getSession().getAttribute("ctx");
		AustinContext.setCurrentContext(actx);

		//item de la sesion
		ISessionContext ses = actx.getSessionContext();
		com.ibm.ccd.content.common.Item itemInternal = (com.ibm.ccd.content.common.Item) ses.getFromSession("myEntry");
		Context ctxAdmin = null;
		try {
			
			if (ctxPIM != null) ctxPIM = PIMContextFactory.getCurrentContext();
			LookupTableManager lkpMan = ctxPIM.getLookupTableManager();
			LookupTable lkp = lkpMan.getLookupTable("System Parameter LKP");
			LookupTableEntry itmLkpUser = lkp.getLookupTableEntry("user.admin.name");
			LookupTableEntry itmLkpPwd = lkp.getLookupTableEntry("user.admin.pwd");
			LookupTableEntry itmLkpCmp = lkp.getLookupTableEntry("company");
			
			String user = (String) itmLkpUser.getAttributeValue("Code_Value_LTS/Value");
			String pwd = (String) itmLkpPwd.getAttributeValue("Code_Value_LTS/Value");
			String cmp = (String) itmLkpCmp.getAttributeValue("Code_Value_LTS/Value");

			ctxAdmin = PIMContextFactory.getContext(user,pwd,cmp);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String pkArticulo = request.getParameter("pkArticulo");
		String pkSociedad = request.getParameter("pkSociedad");
		String sCtgName = request.getParameter("sCtgName");
		String seleccion = request.getParameter("Seleccion");
		String[] aClaves = seleccion.split(",");
		Context ctx = PIMContextFactory.getCurrentContext();
		LookupTableManager lkpMan = ctx.getLookupTableManager();
		LookupTable lkp = lkpMan.getLookupTable("System Parameter LKP");
		LookupTableEntry itmLkpUser = lkp.getLookupTableEntry("user.admin.name");
		LookupTableEntry itmLkpPwd = lkp.getLookupTableEntry("user.admin.pwd");
		LookupTableEntry itmLkpCmp = lkp.getLookupTableEntry("company");
		
		String user = (String) itmLkpUser.getAttributeValue("Code_Value_LTS/Value");
		String pwd = (String) itmLkpPwd.getAttributeValue("Code_Value_LTS/Value");
		String cmp = (String) itmLkpCmp.getAttributeValue("Code_Value_LTS/Value");
		
		
		ctx = PIMContextFactory.getContext(user, pwd, cmp);
		
		boolean newStarted = false;
		
		if (!ctx.inTransaction()){
			newStarted = true;
			ctx.startTransaction();
		} 
		
		ctgMan = ctx.getCatalogManager();
		hyMng = ctx.getHierarchyManager();

		
		Catalog ctg = ctgMan.getCatalog(sCtgName);

		ctg.getProcessingOptions().setAllProcessingOptions(false);
		Catalog	ctgArticulos = ctgMan.getCatalog(ConstSantillana.MAESTRO_ARTICULOS);
		ctg.getProcessingOptions().setAllProcessingOptions(false);
		Item item = ctg.getItemByPrimaryKey(pkArticulo);
		
		Hierarchy hySociedad = hyMng.getHierarchy(ConstSantillana.JERARQUIA_PAISES);
		Hierarchy hyTipologia = hyMng.getHierarchy(ConstSantillana.JERARQUIA_TIPO_DE_PRODUCTO);

		// Cargar la categoria de la jerarquia tipologia del item
		Category catTipologia = item.getCategories(hyTipologia).iterator().next(); 
				
		// La PK de SociedadTipo es la concatenacion del PK de Sociedad y Tipologia
		
		System.out.println("pkSociedad_Tipo: " +  pkSociedad);

		
		System.out.println("voy a  catTipologia: " +  catTipologia.getPrimaryKey());

		
		
		Category catSociedadTipo = hySociedad.getCategoryByPrimaryKey(pkSociedad);
		Collection<SecondarySpec> listaSpecs = catSociedadTipo.getItemSecondarySpecs();
		Iterator <SecondarySpec> itSpecs = listaSpecs.iterator();
		
		String sSpecName = null;
		while (itSpecs.hasNext()) {
			SecondarySpec secSpec = itSpecs.next();
			String name = secSpec.getName();
			if (!name.contains("SEARCH")) {
				sSpecName = name;
			}
		}
		
		
		if(itemInternal == null){
			System.out.println("error cogiendo el item interno");
		}
		
//		EntryNode enPacks = itemInternal.getEntryNode(sSpecPack+"/Packs");
		AttributeInstance atInsPack = item.getAttributeInstance(sSpecName+"/Articulos_Relacionados");
		for(int i=0;i<aClaves.length;i++){
			String sClave = aClaves[i];
			Item elemento = null;
			if(sClave!=null){
				elemento = ctgArticulos.getItemByPrimaryKey(sClave);
			}
			if(elemento!=null){
				/*				EntryNode enGrupoPacks = enPacks.addOccurrence();
				//itemInternal.setAttributeValueUsingPathAndThrowExceptionForInvalidTypeConversion(enGrupoPacks.getExactPath()+"/Articulo_Pack",elemento);
				EntryNode entryNodePackArticulo = itemInternal.getEntryNode(enGrupoPacks.getExactPath()+"/Articulo_Pack");
	
				try{
					System.out.println("Entrynode path : "+entryNodePackArticulo.getExactPath());
					System.out.println("Elemento pk : "+elemento.getPrimaryKey());
					entryNodePackArticulo.setValue(elemento);
				}catch (Exception e){
					System.out.println(e.getMessage());
				}
				try{
					itemInternal.setAttributeValueUsingPathAndThrowExceptionForInvalidTypeConversion(enGrupoPacks.getExactPath()+"/Articulo_Pack",elemento);
				}catch (Exception e){
					System.out.println(e.getMessage());
				}
				try{
					itemInternal.setAttributeValue(enGrupoPacks.getExactPath()+"/Articulo_Pack",elemento.getPrimaryKey());
				}catch (Exception e){
					System.out.println(e.getMessage());
				}
				try{
					itemInternal.setCoreAttr(enGrupoPacks.getExactPath()+"/Articulo_Pack",elemento.getPrimaryKey());
				}catch (Exception e){
					System.out.println(e.getMessage());
				}
				try{
					itemInternal.setGlobalAttribute(enGrupoPacks.getExactPath()+"/Articulo_Pack",elemento.getPrimaryKey());
				}catch (Exception e){
					System.out.println(e.getMessage());
				}

*/
				AttributeInstance atInsPackMulti = atInsPack.addOccurrence();
				item.getAttributeInstance(atInsPackMulti.getPath()+"/Articulo_Relacionado").setValue(ctgArticulos, sClave);
			}
		}
		
		ExtendedValidationErrors valErr = item.save();
		
		if(valErr!=null){
			List<ValidationError> lErrors = valErr.getErrors();
			for (ValidationError validationError : lErrors) {
				System.out.println(validationError.getMessage());
			}
		}else{
			try {
				itemInternal.updateCopy();
//				System.out.println("Attribute1 : "+ itemInternal.getAttributeValue(sSpecPack+"/Packs#0/Articulo_Pack"));
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}

		}
		
		if(newStarted){
			ctx.commit();
		}   
		
		responseContent = "TODO OK";
		
	}
	
	
	
	private JSONArray obtenerDatosFormulario(String sPk, String pkSociedad, String sbWf, String sCtgName) throws PIMSearchException{
		System.out.println("Obtener Info Pack");
		System.out.println("pkSociedad " + pkSociedad);
		JSONArray aListPack = new JSONArray();
		
		if(ctxPIM == null){
			ctxPIM = PIMContextFactory.getCurrentContext();
		}
		
		if(ctgMan==null){
			ctgMan = ctxPIM.getCatalogManager();
		}
		
		// Cargar jerarquias
		if(hyMng == null) {
			hyMng = ctxPIM.getHierarchyManager();
		}
		
		if (caMng == null) {
			caMng = ctxPIM.getCollaborationAreaManager();
		}
		
		Hierarchy hySociedades = hyMng.getHierarchy(ConstSantillana.JERARQUIA_PAISES);
		
		
		// Cargar item del catalogo Articulos
		if(catalogoMaestro==null){
			catalogoMaestro = ctgMan.getCatalog(ConstSantillana.MAESTRO_ARTICULOS);
		}
//		Item item = catalogoMaestro.getItemByPrimaryKey(sPk);
		Category catSociedad = hySociedades.getCategoryByPrimaryKey(pkSociedad);
		String sPaisCode = catSociedad.getParent().getPrimaryKey(); 

		OrderedJSONObject objVacio = new OrderedJSONObject();
		objVacio.put("Key", "NULL");
		objVacio.put("Value", "---NINGUNO---");
		//Rellena el json para el combo del curso
		JSONArray aCursos = new JSONArray();
		aCursos.add(objVacio);
		SearchQuery sqCurso = ctxPIM.createSearchQuery(QUERY_COMBO_CURSO+sPaisCode+CCOMILLA);
		SearchResultSet rsCurso = sqCurso.execute();
		while(rsCurso.next()){
			OrderedJSONObject objCurso = new OrderedJSONObject();
			Item itmCurso = rsCurso.getItem(1);
			objCurso.put("Key", itmCurso.getPrimaryKey());
			objCurso.put("Value", itmCurso.getAttributeValue("Cursos/Valor/es_ES"));
			aCursos.add(objCurso);
		}
		aListPack.add(aCursos);
		
		//Rellena el json para el combo de la asignatura
		JSONArray aAsignaturas = new JSONArray();
		aAsignaturas.add(objVacio);
		SearchQuery sqAsignaturas = ctxPIM.createSearchQuery(QUERY_COMBO_ASIGNATURA+sPaisCode+CCOMILLA);
		SearchResultSet rsAsignaturas = sqAsignaturas.execute();
		while(rsAsignaturas.next()){
			OrderedJSONObject objAsignaturas = new OrderedJSONObject();
			Item itmAsignaturas = rsAsignaturas.getItem(1);
			objAsignaturas.put("Key", itmAsignaturas.getPrimaryKey());
			objAsignaturas.put("Value", itmAsignaturas.getAttributeValue("Asignaturas/Valor/es_ES"));
			aAsignaturas.add(objAsignaturas);
		}
		aListPack.add(aAsignaturas);

		//Rellena el json para el combo del Sello
		JSONArray aSellos = new JSONArray();
		aSellos.add(objVacio);
		SearchQuery sqSello = ctxPIM.createSearchQuery(QUERY_COMBO_SELLO);
		SearchResultSet rsSello = sqSello.execute();
		while(rsSello.next()){
			OrderedJSONObject objsello = new OrderedJSONObject();
			Item itmSello = rsSello.getItem(1);
			objsello.put("Key", itmSello.getPrimaryKey());
			objsello.put("Value", itmSello.getAttributeValue(ConstSantillana.TABLA_GLOBAL_VALOR));
			aSellos.add(objsello);
		}
		aListPack.add(aSellos);

		//Rellena el json para el combo del plan editorial
		JSONArray aPlanes = new JSONArray();
		aPlanes.add(objVacio);
		SearchQuery sqPlan = ctxPIM.createSearchQuery(QUERY_COMBO_PLAN_EDITORIAL);
		SearchResultSet rsPlan = sqPlan.execute();
		while(rsPlan.next()){
			OrderedJSONObject objPlan = new OrderedJSONObject();
			Item itmPlan = rsPlan.getItem(1);
			objPlan.put("Key", itmPlan.getPrimaryKey());
			objPlan.put("Value", itmPlan.getAttributeValue(ConstSantillana.TABLA_GLOBAL_VALOR));
			aPlanes.add(objPlan);
		}
		aListPack.add(aPlanes);
		
		return aListPack;
		
	}
	
	private JSONArray obtenerInfoArticulos (ArrayList <Item> items, Category catSociedad){
		System.out.println("Obtener Info Articulo Pack");

		JSONArray aListPack = new JSONArray();
		for(Item item : items){
			OrderedJSONObject obj = new OrderedJSONObject();
			System.out.println("item " + item.getPrimaryKey());
			
			String sPk = item.getPrimaryKey(); 
			String tituloRelacionado = (String) item.getAttributeValue(sSpecName + "/Titulo_Corto");
			if (tituloRelacionado == null) {
				tituloRelacionado = "-";
			}
			String isbnRelacionado = (String) item.getAttributeValue(sSpecName + "/EAN");
			if(isbnRelacionado == null) isbnRelacionado = "-";
			
			String sello = (String) item.getAttributeValue(sSpecName + "/DESC_Sello"); 
			if (sello == null) {
				sello = "-";
			}
			String tipoproducto = (String) item.getAttributeValue(sSpecName + "/DESC_Tipo_Producto"); 
			if (tipoproducto == null) {
				tipoproducto = "-";
			}
			
			String sLinea = (String) item.getAttributeValue(sSpecName + "/DESC_Linea"); 
			
			String imagen = ItemUtils.getItemMainImageName(item);
			
			LookupTableManager lkpMan = PIMContextFactory.getCurrentContext().getLookupTableManager();
			LookupTable lkp =  lkpMan.getLookupTable(ConstSantillana.LOOKUP_SYSTEM);
			LookupTableEntry lkpEntry = lkp.getLookupTableEntry("company");
			String sCompany = (String) lkpEntry.getAttributeValue("Code_Value_LTS/Value");
			
			
			System.out.println("clave: " + sPk);
			System.out.println("imagen: " + "<img src=\"/suppliers/"+sCompany+"/ctg_files/" + imagen + "\" alt=\"Imagen del articulo.\" width=\"20\" height=\"20\">");
			System.out.println("isbnRelacionado: " + isbnRelacionado);
			System.out.println("titulo: " + tituloRelacionado);
			System.out.println("sello: " + sello);
			System.out.println("linea: " + sLinea);
			
			
			obj.put("pk", sPk);
			obj.put("clave", sPk);
			obj.put("imagen", "<img src=\"/suppliers/"+sCompany+"/ctg_files/" + imagen + "\" alt=\"Imagen del articulo.\" width=\"20\" height=\"20\">");
			
			obj.put("isbn", isbnRelacionado);
			obj.put("titulo", tituloRelacionado);
			obj.put("sello", sello);
			obj.put("linea", sLinea);
		
			 
			
			
			aListPack.add(obj);
		}
	
		
		return aListPack;
	}
}
